package com.gkfreshmart.cloud.utils;

import com.gkfreshmart.cloud.utils.StringUtil;
import com.esotericsoftware.reflectasm.MethodAccess;
import org.beetl.sql.annotation.entity.Column;
import org.beetl.sql.core.query.Query;

import java.lang.reflect.Field;

/**
 * Copyright (C),2019-2020),田坊集市数据科技有限公司
 * FileName: QueryConditionBuilder
 * Author: Bruin
 * Date: 2020/11/1 20:52
 * Description:
 * History:
 * <author>  <time>  <version>   <desc>
 * 作者姓名  修改时间    版本号     描述
 */
public class QueryConditionBuilder<T> {
    /**
     * 通过反射动态构建查询条件
     *
     * @param query
     * @param entity
     */
    public  void queryConditionBuilder(Query<T> query, T entity) {
        T t = entity;
        Field[] declaredFields = t.getClass().getDeclaredFields();
        for (Field field : declaredFields
        ) {
            MethodAccess methodAccess = MethodAccess.get(t.getClass());
            String fieldName = field.getName();
            Object value = methodAccess.invoke(t, "get" + StringUtil.toUpperCaseFirst(fieldName));
            if (value != null && !StringUtil.isBlank(value.toString())) {
                boolean hasColumnAnnotation = field.isAnnotationPresent(Column.class);
                if (hasColumnAnnotation) {
                    //特殊字段通过注解填充
                    String columnName = field.getAnnotation(Column.class).value();
                    query.andEq(columnName, value);
                } else {
                    query.andEq(StringUtil.camelToUnderline(fieldName), value);
                }
            }
        }
    }
}
